package com.mec.web.y2012.ebookshop;

import static com.mec.web.y2012.ebookshop.EBookshopConstants.*;

import java.io.IOException;
import java.util.Vector;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * Servlet implementation class ShoppingServlet
 * doc-base: file:/C:/glassfish3/glassfish/docs/api/
 * doc-base2: file:/C:/Users/MEC/Documents/Date/tomcat-7.0-doc/servletapi/
 */
@WebServlet("/ShoppingServlet")
public class ShoppingServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2467044831274872856L;
	@Override
	public void init(ServletConfig conf) throws ServletException {
		super.init(conf);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession(true);
		//
		Vector<Book> shopList = (Vector<Book>) session.getAttribute(ATTR_BOOKCART);
		String do_this = req.getParameter(OPERATION_TAG);
		//
		if(null == do_this){
			Vector<String> blist = new Vector<String>();
			//
			blist.addElement("Beginning JSP, JSF, and Tomcat. Zambon/Sekler $39.99");
			blist.addElement("Beginning JBoss Seam. Nusairat $39.99");
			blist.addElement("Founder at Work. Livingston $25.99");
			blist.addElement("Business Software. Sink $24.99");
			blist.addElement("Foundations of Security. Daswani/Kern/Kesavan $39.99");
			session.setAttribute(ATTR_BOOKLIST, blist);
			//
			ServletContext sc = getServletContext();
			RequestDispatcher rd = sc.getRequestDispatcher(PAGE_BOOKSELECT);
			rd.forward(req, resp);
		}else{
			//
			if(do_this.equals(OPERATION_CHECKOUT)){
				float dollars = 0;
				int books = 0;
				for(int i = 0 ; i < shopList.size(); ++i){
					Book aBook = (Book) shopList.elementAt(i);
					float price = aBook.getPrice();
					int qty = aBook.getQuantity();
					dollars += price * qty;
					books += qty;
				}
				//
				req.setAttribute("dollars", new Float(dollars).toString());
				req.setAttribute("books", new Integer(books).toString());
				//
				ServletContext sc = getServletContext();
				RequestDispatcher rd = sc.getRequestDispatcher(EBookshopConstants.PAGE_CHECKOUT);
				rd.forward(req, resp);
				//
			}else {
				
				if(do_this.equals(OPERATION_REMOVE)){
					String pos = req.getParameter("position");
					shopList.removeElementAt(Integer.parseInt(pos));
					//logger.info("remove book at-> " + pos);
					//logger.info("shopList.size -> " + shopList.size());
				}else if(do_this.equals(OPERATION_ADD)){
					boolean found = false;
					Book aBook = getBook(req);
					if(null == shopList){
						shopList = new Vector<Book>();
						shopList.addElement(aBook);
					}else{
						for(int i = 0 ; i < shopList.size() && !found; ++i){
							Book b = shopList.elementAt(i);
							if(b.getTitle().equals(aBook.getTitle())){
								b.setQuantity(b.getQuantity() + aBook.getQuantity());
								shopList.setElementAt(b, i);
								found = true;
							}
						}
						//
						if(!found){
							shopList.addElement(aBook);
						}
					}
				}
				//
				session.setAttribute(ATTR_BOOKCART, shopList);
				ServletContext sc = getServletContext();
				RequestDispatcher rd = sc.getRequestDispatcher(PAGE_BOOKSELECT);
				rd.forward(req, resp);
			}
		}
	}


	private Book getBook(HttpServletRequest req){
		String myBook = req.getParameter("book");
		int n = myBook.indexOf('$');
		String title = myBook.substring(0, n);
		String price = myBook.substring(n+1);
		String qty = req.getParameter("qty");
		return new Book(title, Float.parseFloat(price), Integer.parseInt(qty));
	}
	private static final Logger logger = 
			Logger.getLogger(ShoppingServlet.class);
}
